<?
class usersAjaxUsers extends ActionHandler
{
    function details()
    {
        global $dbLink, $user;
        if ($user->isEnabledTo("read", $module->id))
        {
            global $dbLink;
            $myUser = new adminUser();
            $myUser->setDBLink($dbLink);
            $myUser->get((int)$_GET["userID"]);
            $response = array("success" => true, "data"=> $this->_getUserData($myUser));
        }
        else $response["message"] = $lang->translate("user_action_denied");
        echo json_encode($response);
    }

    function save_details()
    {
        global $dbLink, $user;
        if ($user->isEnabledTo("write", $module->id))
        {
            $myUser = new adminUser();
            $myUser->setDBLink($dbLink);
            
            if(empty($_REQUEST["password"]))
                unset($myUser->_arFields[array_search('password',$myUser->_arFields)]);
                
            $myUser->set($_POST);
            $myUser->userID_modified = $user->getID();
            $myUser->userID_created = $user->getID();
            $_REQUEST["userID"] ?  $myUser->update() : $myUser->create();

            $roles = array();
            if(isset($_REQUEST["roles"])) { // si no está seteado, entonces no tiene ningun role
                foreach($_REQUEST["roles"] as $roleID=>$v) {
                    $roles[] = mysql_escape_string(implode(" ",explode("_",$roleID)));
                }
            }
            $myUser->setRoles($roles);
            $response = array("success" => true, "data"=> $this->_getUserData($myUser));
        }
        else $response["message"] = $lang? $lang->translate("user_action_denied") : 'user_action_denied';
        echo json_encode($response);
    }

    function delete()
    {
        global $dbLink, $user;
        if ($user->isEnabledTo("write", $module->id))
        {
            $myUser = new adminUser();
            $myUser->setDBLink($dbLink);
            $arPIDs = is_array($_POST['userID'])? $_POST['userID'] : array($_POST['userID']);
            foreach($arPIDs AS $myUserID)
            {
                if ($user->getID() == (int)$myUserID) continue;
                if ($myUser->get($myUserID) && $myUser->delete()) continue;
                $response["message"] = $lang->translate("error_delete_record"). mysql_error();
                break;
            }
        }
        else $response["message"] = $lang->translate("user_action_denied");
        $response["success"] = $response["message"]? false : true;
        echo json_encode($response);
    }

    function user_list()
    {
        global $dbLink, $user, $module;
        if ($user->isEnabledTo("read", $module->id))
        {
            if ($_POST['query'])
            {
                // Useros
                $squery = new SearchQuery();
                $squery->setQueryString($_POST['query']);  // Or $queryString or whatever your string variable is
                $squery->isExact = false;     // if false, SearchQuery searchs like '%$query%', else '$query'
                $squery->table = "";
                $squery->setFields(array("username", "name", "last_name", "email")); // Setting up search fields
                $sqlWhere = $squery->build();
            }

            $sql  = "SELECT SQL_CALC_FOUND_ROWS u.*, GROUP_CONCAT(DISTINCT roleID ORDER BY roleID DESC SEPARATOR ', ') as roles";
            $sql .= " FROM users As u LEFT JOIN users_users_roles AS ur ON u.userID = ur.userID";
            $sql .= $sqlWhere? ' WHERE '. $sqlWhere : ' ';
            $sql .= " GROUP BY u.userid";
            $sql .= $_POST['sort']? " ORDER BY ". txt2sql($_POST['sort'], $dbLink) ." ". txt2sql($_POST['dir'], $dbLink) ." " : "";
            $sql .= " LIMIT ". (int) $_POST['start'] .", ". ((int)$_POST['limit']<$module->numMaxListedRows&&(int)$_POST['limit']!=0? (int)$_POST['limit'] : $module->numMaxListedRows);
            $result = mysql_query($sql, $dbLink);
            echo mysql_error();

            $myUser = new adminUser();
            while($row = mysql_fetch_assoc($result))
            {
                $myUser->set($row);
                $response["users"][] = array("userID"       => $myUser->getID(),
                                             "username"     => $myUser->username,
                                             "name"         => $myUser->name,
                                             "last_name"    => $myUser->last_name,
                                             "email"        => $myUser->email,
                                             "active"       => $myUser->active,
                                             "roles"        => $row['roles'],
                                             "superuser"    => $myUser->superuser,
                                             "last_login"   => dateFormat($myUser->last_login),
                                             "date_created" => dateFormat($myUser->date_created));
            }
            $sql = "SELECT FOUND_ROWS()";
            list($response["totalCount"]) = mysql_fetch_row(mysql_query($sql, $dbLink));
            if($response["totalCount"]==0) $response["users"] = array();
        }
        else $statusMsg = $lang->translate("user_action_denied");
        echo json_encode($response);
    }

    private function _getUserData($myUser)
    {
        global $dbLink;

        $data = array();
        $data['userID'] = $myUser->userID;

        $user_created = new adminUser();
        $user_created->setDBLink($dbLink);
        $user_created->get($myUser->userID_created);

        $data["user_created"] = $user_created->username;

        $user_modified = new adminUser();
        $user_modified->setDBLink($dbLink);
        $user_modified->get($myUser->userID_modified);

        $data["user_modified"] = $user_modified->username;

        $myUsersFieldsName = $myUser->getFieldNames();
        foreach($myUsersFieldsName as $fieldName)
        {
            $data[$fieldName] = $myUser->$fieldName;
        }
        
        $data["password"] = "";
        $data["active"] = ($data["active"] == "Y");
        $data["superuser"] = ($data["superuser"] == "Y");

        $userRoles = $myUser->getRoles();
        $r = getAllRoles();
        $roles = array();
        foreach($r as $role) {
            $roles[] = $role->roleID;
        }

        foreach($roles as $role) {
            $data["roles[".implode("_", explode(" ", $role))."]"] = in_array($role, $userRoles) ? true : false;
        }

        return $data;
     }
}

?>
